package com.zx.deploy.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.zx.deploy.common.exception.BusinessException;
import com.zx.deploy.common.utils.CommonUtil;
import com.zx.deploy.common.utils.DatetimeUtil;
import com.zx.deploy.common.utils.PackUtil;
import com.zx.deploy.common.utils.RuntimeUtil;
import com.zx.deploy.config.DeployConfig;
import com.zx.deploy.model.SpeedProgress;
import com.zx.deploy.service.DataBaseService;

/**
 * 基于环境 -脚本数据库操作实现方式
 * 
 * @author jbyu
 *
 */
@Service("EnvDataBaseService")
public class EnvDataBaseServiceImpl implements DataBaseService {

	@Value("${spring.datasource.username}")
	private String userName;

	@Value("${spring.datasource.password}")
	private String password;

	/**
	 * 备份数据库
	 */
	public SpeedProgress backupDatabase(DeployConfig config) {
		String cmd = String.format(config.mysql_mysqldump_cmdStr, userName, password,
				config.database_name, config.backups_database_path, DatetimeUtil.getCurrentDateTime("yyyyMMdd_HHmmss"));
		String result = RuntimeUtil.execCmd(cmd,true,true);
		SpeedProgress sp = new SpeedProgress(100, "备份数据库");
		sp.setInfo(result);
		return sp;
	}

	/**
	 * 回滚数据库
	 * 
	 * @param callBackSql
	 * @return
	 */
	public SpeedProgress rollbackDatabase(String callBackSql, DeployConfig config) {
		SpeedProgress sp=new SpeedProgress(0, "解压文件");
		String back_file_path=config.backups_database_path+callBackSql;
		String sql_file_path=back_file_path.replace(".gz", "");
		//如果未压缩，不解压
		if (back_file_path.contains(".gz")) {
			try {
				PackUtil.unGzipFiles(new File(back_file_path), sql_file_path);
			} catch (Exception e) {
				sp.setInfo("解压文件失败");
				throw new BusinessException("解压文件失败");
			}
		}
		sp.setInfo(50, "恢复数据库");
		String rollback_cmd=String.format(config.mysql_rollback_cmdStr,userName, password,
				config.database_name,sql_file_path);
		String result2 = RuntimeUtil.execCmd(rollback_cmd,true,true);
		sp.setInfo(100,"恢复结束",result2);
		return sp;
	}

	/**
	 * 执行脚本
	 */
	public void executeSqlIgnoreError(DeployConfig config, SpeedProgress speed) {
		String script_path = config.soft_file_path + config.soft_unzip_name + File.separator + config.soft_sql_name;
		String exe_cmd = config.shell_path.concat(config.soft_sql_shell) + " %s %s %s";
		String result = RuntimeUtil.execCmd(String.format(exe_cmd, script_path, userName, password),true,true);
		speed.setInfo(result);
	}

	/**
	 * 执行脚本
	 */
	public void executeSql(DeployConfig config, SpeedProgress speed) {
		String exe_cmd = config.mysql_exe_cmdStr;
		String script_path = config.soft_file_path + config.soft_unzip_name + File.separator + config.soft_sql_name
				+ File.separator;
		File file = new File(script_path);
		File[] files = file.listFiles();
		List<String> sqlNames = new ArrayList<>();
		if (files != null && files.length > 0) {
			Arrays.asList(files).stream().forEach(t -> sqlNames.add(t.getName()));
		}
		for (String script : sqlNames) {
			String result = RuntimeUtil.execCmd(String.format(exe_cmd, userName, password, script_path + script),true,true);
			speed.setInfo(result);
			if (result != null && result.contains("ERROR")) {
				speed.setInfo("执行脚本异常");
				throw new BusinessException("执行脚本异常");
			}
			CommonUtil.sleep(100);
		}
	}
}
